import { ref } from 'vue'
import { getParkEnterpriseListApi, getParkEnterpriseDetailApi, type ParkEnterpriseInfo, type ParkEnterpriseListResponse, type ParkEnterprisePageQuery } from '~/server/parkEnterpriseApi'
import { PageQuery } from '~/types/global'

export const useParkEnterprise = () => {
    const loading = ref(false)
    const enterpriseList = ref<ParkEnterpriseInfo[]>([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)

    /**
     * 获取园区企业列表
     * @param params 查询参数
     * @returns 园区企业列表数据
     */
    const fetchEnterpriseList = async (params?: Partial<PageQuery & { keyword?: string; status?: number }>) => {
        try {
            loading.value = true
            const queryParams: ParkEnterprisePageQuery = {
                page: params?.page || currentPage.value,
                limit: params?.limit || pageSize.value,
                keyword: params?.keyword,
                status: params?.status
            }

            const response = await getParkEnterpriseListApi(queryParams)
            console.log('API原始响应:', response)

            // 根据实际API返回的数据结构处理
            const apiData = response.data?.value || response.data || response
            console.log('处理后的数据:', apiData)

            // 检查响应结构
            if (apiData && typeof apiData === 'object') {
                if (apiData.code === 200 && apiData.data) {
                    // 标准API响应格式
                    const data = apiData.data
                    enterpriseList.value = data?.list || []
                    total.value = data?.total || 0
                    return data
                } else if (apiData.list) {
                    // 直接数据格式
                    enterpriseList.value = apiData.list || []
                    total.value = apiData.total || 0
                    return apiData
                } else {
                    console.error('未知的API响应格式:', apiData)
                    throw new Error('API响应格式不正确')
                }
            } else {
                throw new Error('API调用失败: 响应数据格式错误')
            }
        } catch (error) {
            console.error('获取园区企业列表失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 获取园区企业详情
     * @param id 企业ID
     * @returns 园区企业详情数据
     */
    const fetchEnterpriseDetail = async (id: number): Promise<ParkEnterpriseInfo> => {
        try {
            loading.value = true
            const response = await getParkEnterpriseDetailApi(id)
            const data = response.data.value as ParkEnterpriseInfo
            return data
        } catch (error) {
            console.error('获取园区企业详情失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 刷新园区企业列表
     * @returns 园区企业列表数据
     */
    const refreshEnterpriseList = () => {
        return fetchEnterpriseList()
    }

    /**
     * 处理分页变化
     * @param page 页码
     * @param size 每页数量
     * @returns 园区企业列表数据
     */
    const handlePageChange = (page: number, size?: number) => {
        currentPage.value = page
        if (size) {
            pageSize.value = size
        }
        return fetchEnterpriseList()
    }

    /**
     * 搜索园区企业
     * @param keyword 搜索关键词
     * @returns 园区企业列表数据
     */
    const searchEnterprises = (keyword: string) => {
        currentPage.value = 1
        return fetchEnterpriseList({ keyword })
    }

    /**
     * 按状态筛选园区企业
     * @param status 状态
     * @returns 园区企业列表数据
     */
    const filterByStatus = (status: number) => {
        currentPage.value = 1
        return fetchEnterpriseList({ status })
    }

    return {
        loading,
        enterpriseList,
        total,
        currentPage,
        pageSize,
        fetchEnterpriseList,
        fetchEnterpriseDetail,
        refreshEnterpriseList,
        handlePageChange,
        searchEnterprises,
        filterByStatus
    }
}
